import os,json,sys
from flask import Flask,render_template, g, request, redirect,url_for,send_from_directory
from json_builder import success_result
import subprocess


app = Flask(__name__,static_folder='static')

BASEDIR = os.path.abspath(os.path.dirname(__file__))
reload(sys)
sys.setdefaultencoding('utf-8')


ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/lottery')
def lottery():
    return render_template('lottery.html')

@app.route('/setting')
def setting():
    return render_template('index.html')

@app.route('/showtable')
def showtable():
    return render_template('winners.html')

@app.route('/gettabledata',methods=['GET'])
def gettabledata():
    f = open(BASEDIR + '/static/winners.json', 'r')
    setting = json.load(f)
    f.close()
    return json.dumps(setting,ensure_ascii=False)

@app.route('/getsetting',methods=['GET'])
def getsetting():
    f = open(BASEDIR + '/static/setting.json', 'r')
    setting = json.load(f)
    f.close()
    return success_result(json.dumps(setting,ensure_ascii=False))

@app.route('/savesetting',methods=['POST'])
def savesetting():
    data = request.get_json()
    setting_str = json.dumps(data, ensure_ascii=False)
    f = open(BASEDIR + '/static/setting.json', 'w')
    f.write(setting_str);
    f.close();
    return 'hello'


@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        file.save(os.path.join("", filename));
        file_url = url_for('uploaded_file', filename=filename)
        return html + '<br><img src=' + file_url + '>'


@app.route('/getallperson',methods=['GET'])
def getallperson():
    f = open(BASEDIR + '/static/allperson.json', 'r')
    setting = json.load(f)
    f.close()
    return success_result(json.dumps(setting,ensure_ascii=False))


@app.route('/saveallperson',methods=['POST'])
def saveallperson():
    data = request.get_json()
    setting_str = json.dumps(data, ensure_ascii=False)
    f = open(BASEDIR + '/static/allpersontwo.json', 'w')
    f.write(setting_str);
    f.close();
    return success_result();

@app.route('/testpython',methods=['POST'])
def testpython():
    data = request.get_json()
    print type(data)
    print data['commond'];
    tt = os.popen('echo "zyp.123" | sudo -S '+data['commond'])
    result = tt.read();
    return success_result(result)

@app.route('/execCommond',methods=['POST'])
def execCommond():
    data = request.get_json()
    print type(data)
    print data['commond'];
    tt = os.popen(data['commond'])
    result = tt.read();
    return success_result(result)

if __name__ == '__main__':
    app.run(debug=True)
